package wangwenjun.phase3.concurrentcollections.copyonwrite;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author ChangLiang
 * @date 2020/6/27
 */
@Slf4j
public class AppV2Test {

    @Test
    @DisplayName("test")
    public void test() {
        // 使用双括弧语法（double-brace syntax）建立并初始化一个List
        // The first brace creates a new Anonymous Inner Class.
        // The second set of brace creates an instance initializers like static block in Class.

        List<String> list = new CopyOnWriteArrayList<String>() {
            {
                add("1");
                add("2");
                add("3");
                add("4");
                add("5");
            }
        };

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            log.info("list is {}", list);
            // Iterator.next 调用了 Iterator.checkForComodification方法
            // 而异常就是checkForComodification方法中抛出的
            String element = iterator.next();
            log.info("current element is {}", element);
            if (StringUtils.equals("2", element)) {
                list.remove("5");
            }
            if (StringUtils.equals("3", element)) {
                list.add("3 found");
            }
            log.warn("finish one loop");
        }
    }
}
